<script setup>
import { to } from '@/utils/routerUtil';
import { format } from 'date-fns';

defineProps({
  item: {
    type: Object,
    required: true
  }
});

// 安全解析 JSON 的增强方法
const safeParseJSON = (str, fallback = []) => {
  try {
    const sanitized = str
      .replace(/([^\["\]])(\w+)([^\]"])/g, '"$2"') 
      .replace(/'/g, '"');
    return JSON.parse(sanitized);
  } catch (error) {
    console.warn('JSON 解析失败:', error);
    return fallback;
  }
};

const getLabelByValue = (value) => ({
  0: '客户退换', 1: '客户送修', 2: '客供料', 3: '进货物料',
  4: '外修送回', 5: '代工交货', 7: 'PCB', 6: '其他'
})[value] || '未知';

const getColorByValue = (value) => ({
  0: '#ff7f50', 1: '#1e90ff', 2: '#32cd32', 3: '#ffa500',
  4: '#9370db', 5: '#20b2aa', 7: '#ff69b4', 6: '#a9a9a9'
})[value] || '#fdc71c';

const statusColor = {
  '待确认': '#f35443',
  '已处理': '#50fa6d',
  '待入库': '#1e90ff',
  '待测试': '#20b2aa'
};
</script>

<template>
  <div class="bg-white rounded-lg shadow-sm p-4 w-[94%] mb-4 text-base">
    <!-- 头部：编号 + 状态 -->
    <div class="flex justify-between items-start mb-4">
      <div>
        <div class="flex items-center gap-2">
          <h2 class="text-[10px] font-bold cursor-pointer hover:text-blue-600"
              @click="to(`preregisterinfo?id=${item.sPreregisterNo}`)">
            {{ item.sPreregisterNo }}
            <img v-if="item.zType !== '已处理'" 
             @click="to(`updatearrive?id=${item.sPreregisterNo}`)"
             class="cursor-pointer hover:opacity-75 transition-opacity"
             width="15" 
             height="15" 
             src="/arrive/修改.png" />
          </h2>
          <VanTag :color="getColorByValue(item.nType)" 
                 class="text-sm px-3 py-1">
            {{ getLabelByValue(item.nType) }}
          </VanTag>
        </div>
        <p class="text-[8px] text-gray-600 mt-1">
          登记时间：{{ format(new Date(item.dPreregisterTime), "yyyy-MM-dd HH:mm") }}
        </p>
      </div>
      
      <div class="flex items-center gap-2">
        <VanTag :color="statusColor[item.zType] || '#fdc71c'"
               class="text-sm px-3 py-1">
          {{ item.zType }}
        </VanTag>
       
      </div>
    </div>

    <!-- 主体内容 -->
    <div class="flex gap-4">
      <!-- 图片展示 -->
      <div class="flex-shrink-0">
        <EImage :width="'140px'" 
               :height="'160px'"
               :photo-url="item.sPhotoUrl == '' ? '[]' : item.sPhotoUrl"
               class="rounded-lg border" />
      </div>

      <!-- 详细信息 -->
      <div class="flex-1 space-y-3">
        <!-- 基础信息 -->
        <div>
          <h3 class="text-[10px] font-semibold">{{ item.sProductName || '未命名产品' }}</h3>
          <p class="text-[8px] text-gray-600">{{ item.sProductNo }}</p>
        </div>

        <!-- 关键数据 -->
        <div class="grid grid-cols-2 gap-3 text-sm">
          <div>
            <span class="text-[10px] text-gray-600">登记数量：{{ item.nPreregisterNum || 0 }}</span>
          </div>
          
          <div v-if="item.serialList">
            <span class="text-gray-600 text-[10px]">序列号：{{ safeParseJSON(item.serialList)[0] }}</span>
          </div>
        </div>

        <!-- 采购信息 -->
        <div v-if="item.purchase" class="bg-gray-50 p-3 rounded">
          <p class="text-[10px] font-semibold text-gray-800 mb-2">采购信息</p>
          <div class="grid grid-cols-2 mt-[8px] text-gray-600 gap-4 text-[10px]">
            <div>单号：{{ item.purchase.sPurchaseNumber }}</div>
            <div>名称：{{ item.purchase.sPurchaseName }}</div>
            <div>数量：{{ item.purchase.nPurchaseQuantity }}</div>
            <div>状态：{{ ['待处理','进行中','已完成'][item.purchase.nStatus] }}</div>
          </div>
        </div>

        <!-- 客户信息 -->
        <div v-if="item.customer" class="bg-gray-50 p-3 rounded">
          <p class="text-[12px] font-semibold text-gray-800 mb-2">客户信息</p>
          <div class="grid grid-cols-2 mt-[8px] text-gray-600 gap-5 leading-[10px] text-[10px]">
            <div>{{ item.customer.sNameCn }}</div>
            <div>{{ item.company?.sName }}</div>
            <div v-if="item.customer.sMobilePhone1">
              联系方式：{{ item.customer.sMobilePhone1 }}
            </div>
          </div>
        </div>
      </div>
    </div>

    <!-- 扩展信息 -->
    <div class="mt-4 space-y-3">
      <!-- 测试结果 -->
      <div v-if="item.nGoodNum !== undefined" class="bg-blue-50 flex flex-col p-8 gap-[8px] rounded">
        <div class="text-[10px] font-semibold text-blue-800">质量检测</div>
        <div class="grid grid-cols-2 gap-3 text-[10px] mt-2">
          <div>测试方法：{{ item.sTestMethod || '暂无' }}</div>
          <div class="flex gap-4">
            <span class="text-green-600">良品：{{ item.nGoodNum }}</span>
            <span class="text-red-600">不良品：{{ item.nBadNum }}</span>
          </div>
        </div>
      </div>

      <!-- 备注信息 -->
      <div v-if="item.sTypeRemark || item.sCustomerRemark" 
           class="bg-yellow-50 flex flex-col p-8 gap-[8px] rounded">
           <div class="text-[12px] font-semibold text-yellow-800">备注信息</div>
        <div class="text-[10px] mt-2">
          <div v-if="item.sTypeRemark">{{ item.sTypeRemark }}</div>
          <div v-if="item.sCustomerRemark">客户备注：{{ item.sCustomerRemark }}</div>
        </div>
      </div>
    </div>

    <!-- 操作按钮 -->
    <div class="flex justify-end gap-3 mt-4">
      <VanButton v-if="item.zType === '待入库'"
                size="small " 
                round
                type="primary"
                @click="to(`inStorage?id=${item.sPreregisterNo}&no=${item.sProductNo}&num=${item.nPreregisterNum}`)"
                class="text-sm">
        确认入库
      </VanButton>
      
      <VanButton v-if="item.zType === '待测试'"
                size="small "
                round
                type="success"
                @click="to(`registerTest?id=${item.sPreregisterNo}`)"
                class=" text-sm">
        填写测试
      </VanButton>
    </div>
  </div>
</template>